<template>
	<view class="container">
		<uni-nav-bar dark :fixed="true" shadow bgimage="linear-gradient(to right, #4facfe 0%, #00f2fe 100%)" status-bar
			left-icon="left" left-text="返回" title="添加商品" @clickLeft="back" />
		<view class="uni-nav-bar-empty-v"></view>
		<form @submit="submitForm">
			<view class="form-item">
				<view class="grace-title-border"></view>
				<text class="label">商品名称：</text>
				<input type="text" v-model="product.productName" />
			</view>
			<view class="form-item">
				<view class="grace-title-border"></view>
				<text class="label">商品价格：</text>
				<input type="digit" v-model="product.price" />
			</view>

			<view class="form-item">
				<view class="grace-title-border"></view>
				<text class="label" style="width: 80%;">商品图片(可多张)：</text>
				<graceSelectImg :maxFileNumber="9" @removeImg="removeImg" @change="imgsChange" :imgLists="imgs">
				</graceSelectImg>
			</view>
			<view style="height: 1rpx;margin-bottom: 100rpx;"></view>
			<view class="submit-button">
				<button type="primary" class="grace-button" @click="addProduct">
					<text class="grace-icons" style="padding-right:12rpx;"></text>添加
				</button>
			</view>
			<!-- 利用canvas裁剪 -->
			    <canvas
			      v-for="(item, index) in cropImgWidths"
			      :key="index"
			      :canvas-id="'myCanvas' + index"
			      :style="{ position: 'absolute', left: (-1000 * index - 2000) + 'px', width: item + 'px', height: item + 'px' }"
			    ></canvas>
		</form>
	</view>
</template>

<script>
	import tabBar from '@/components/tabBar/tabBar.vue';
	import graceSelectImg from "@/graceUI/components/graceSelectImg.vue";
	import productApi from '@/api/product.js';
	import {
		batchUploadPorductImg
	} from '@/api/api.js';
	export default {
		components: {
			graceSelectImg
		},
		data() {
			return {
				productTypes: [{
						value: '01',
						label: '食品'
					},
					{
						value: '02',
						label: '服饰'
					}
				],
				merchantId: '',
				productTpyeIndex: 0,
				product: {
					productName: '',
					type: null,
					title: '',
					merchantId: '',
					price: '',
					unit: '',
					description: '',
					imgs: [],
					labels: ['']
				},
				imgs: [],
				cropImgWidths:[500,500,500,500,500,500,500,500]
			};
		},
		onLoad: function(options) {
			console.log(options.merchantId)
			this.product.merchantId = options.merchantId;
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			pickProductType: function(e) {
				console.log(e)
				this.productTpyeIndex = e.detail.value;
				this.product.type = this.productTypes[e.detail.value].value;
			},
			addLabel() {
				this.product.labels.push('');
			},
			delLabel(index) {
				this.product.labels.splice(index, 1);
			},
			addProduct() {
				console.log("addProduct")
				uni.showLoading({
					title: '添加中',
					icon: 'loading'
				});
				let paths = this.imgs.map(o => o.url);
				batchUploadPorductImg(paths).then(ress => {
					console.log(ress)
					let imgs = ress.map(o => ({
						response: o
					}));
					this.product.imgs = imgs
					console.log(this.product)
					productApi.add(this.product).then(response => {
						uni.showToast({
							title: '完成',
							icon: 'success',
							duration: 1500
						}).then(res => {
							uni.navigateBack({
								delta: 1
							})
						});
					}).catch(error => {
						uni.showToast({
							title: '失败',
							icon: 'fail',
							duration: 1500
						});

					});
				});
			},
			async imgsChange() {
				// 正方形中心裁剪
				// const imgs = await Promise.all(this.cropMultipleImages(this.imgs));
				// this.imgs = imgs
			},
			cropMultipleImages(imgs) {
				var that = this
				return imgs.map((img, index) => {
					return new Promise((resolve, reject) => {
						let mycanvas = 'myCanvas' + index
						const ctx = uni.createCanvasContext(mycanvas, this);
						uni.getImageInfo({
							src:img.url,
							success: (imageInfo) => {
								console.log(imageInfo)
								const { width, height } = imageInfo;
								const sideLength = Math.min(width, height);
								that.cropImgWidths[index] = sideLength
								console.log("sideLength", sideLength)
								const centerX = width / 2;
								const centerY = height / 2;
								const startX = centerX - sideLength / 2; // 裁剪起始点X坐标
								const startY = centerY - sideLength / 2; // 裁剪起始点Y坐标
								ctx.drawImage(img.url, startX, startY, sideLength, sideLength, 0, 0, sideLength, sideLength); // 假设裁剪成正方形，宽高都是300px
								ctx.draw(false, () => {
									uni.canvasToTempFilePath({
										canvasId: mycanvas,
										success: (res) => {
											img.url = res.tempFilePath
											console.log("img.url", img.url)
											resolve(img); // 解析为单个图片的路径
										},
										fail: (error) => {
											reject(error); // 在出错时拒绝Promise
										}
									}, this);
								});		
							}
						})

					});
				});
			}
		}
	};
</script>

<style>
	page {
		background-color: white;
	}

	.container {
		padding: 20px;
	}

	.form-item {
		margin-bottom: 20px;
		display: flex;
		justify-content: left;
		align-items: center;
		flex-wrap: wrap;

	}

	.label {
		padding-top: 5rpx;
		display: block;
		margin-bottom: 5px;
		color: #666666;
	}

	input {
		width: 100%;
		height: 40px;
		padding: 5px 10px;
		box-sizing: border-box;
		background-color: #f8f9f9;
		border: solid 1rpx #f7f7f7;
		border-radius: 10rpx;
		color: #2a2a2a;
		display: flex;
		justify-content: left;
		align-items: center;
		flex-wrap: wrap;
	}

	.pick-container {
		width: 70%;
		height: 40px;
		padding: 5px 10px;
		box-sizing: border-box;
		background-color: #fcfcfc;
		border: solid 1rpx #f7f7f7;
		border-radius: 10rpx;
		color: #2a2a2a;
		display: flex;
		justify-content: left;
		align-items: center;
		flex-wrap: wrap;
	}

	textarea {
		width: 70%;
		padding: 5px 10px;
		box-sizing: border-box;
		background-color: #fcfcfc;
		border: solid 1rpx #f7f7f7;
		border-radius: 10rpx;
		color: #2a2a2a;
	}

	button {
		width: 100%;
		height: 40px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 5px;
	}

	.submit-button {
		padding-inline: 20rpx;
		position: fixed;
		left: 0;
		bottom: 50rpx;
		width: calc(100vw - 40rpx);
		height: 50px;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
	}
</style>